import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'
import { _HttpClient } from '@delon/theme'
import { map } from 'rxjs/operators'

import { PageService } from '@shared/services/page.service'
import { CommonAcquirerService } from '@shared/services/acquirer.service'
import { AcquirerQr, IUpdateAcquirerQRFeature } from '@shared/interfaces/acquirer'
import { DetailTabClass } from '@shared/classes/DetailTabClass'
import { ETabScrollStatus } from '@shared/enums'
import { AcquirerService } from '../../acquirer.service'
import { ActivatedRoute } from '@angular/router'
import { NzMessageService } from 'ng-zorro-antd'
import { I18NService } from '@core'

@Component({
  selector: 'app-acquirer-detail-tab-func-qr',
  templateUrl: './tab-func-qr.component.html',
})
export class AcquirerDetailTabFuncQrComponent extends DetailTabClass<AcquirerQr> implements OnInit {
  // tradeFunction: IBaseInfoColumn[]
  // tradeTypes: IBaseInfoColumn[]
  // tradeWallet: IBaseInfoColumn[]

  fields = {
    TradeFunction: '1',
    TradeType: '2',
    TradeWallet: '3'
  }
  params: IUpdateAcquirerQRFeature = {
    version: 0,
    feature: null
  }

  @ViewChild('tpRefund') tpRefund: TemplateRef<any>
  @ViewChild('tpSupportTips') tpSupportTips: TemplateRef<any>
  @ViewChild('tpFixAmount') tpFixAmount: TemplateRef<any>
  @ViewChild('tpTransactionTypes') tpTransactionTypes: TemplateRef<any>
  @ViewChild('tpWxp') tpWxp: TemplateRef<any>
  @ViewChild('tpAlp') tpAlp: TemplateRef<any>

  @ViewChild('operatorFunction') operatorFunction: TemplateRef<any>
  @ViewChild('operatorType') operatorType: TemplateRef<any>
  @ViewChild('operatorWallet') operatorWallet: TemplateRef<any>

  transactionTypes = [
    {label: '下单', value: 'string', checked: false},
    {label: '预下单', value: 'AC01', checked: false},
    {label: '收款码', value: 'AE01', checked: false},
    {label: '退款', value: 'EP01', checked: false},
    {label: 'APP支付', value: 'DP01', checked: false},
    {label: '小程序支付', value: 'DP01', checked: false}
  ]

  constructor(
    public pageService: PageService,
    public route: ActivatedRoute,
    private messageService: NzMessageService,
    private commonAcquirerService: CommonAcquirerService,
    private acquirerService: AcquirerService,
    private i18n: I18NService,
  ) {
    super(pageService, route)
  }

  ngOnInit() {
    this.initialData()
    // this.isEdit[this.OPERATOR_TYPE.TradeFunction] = false
    // this.isEdit[this.OPERATOR_TYPE.TradeType] = false
    // this.isEdit[this.OPERATOR_TYPE.TradeWallet] = false
  }

  initialData() {
    this.commonAcquirerService.viewAcquirer$.value$.subscribe(acquirer => {
      // Reset columns
      this.initialColumns()

      this.data = acquirer.institution.qr
      this.params.version = acquirer.institution.version
      // if (!qr.tradeTypes) {
      //   return
      // }
      // if (qr.tradeTypes.length <= 0) {
      //   return
      // }
      this.setEdit(this.fields.TradeFunction, 1)
      // this.setEdit(this.fields.TradeType, 1)
      this.setEdit(this.fields.TradeWallet, 1)

      this.setupTradeFunctionColumns(this.data)
      this.setupTradeWalletColumns(this.data)
      this.setupIdForColumn(this.fields)
      // this.transactionTypes.map(tran => {
      //   tran.checked = qr.tradeTypes.includes(tran.value)
      // })
      // this.columns[this.fields.TradeType].push([
      //   {
      //     span: 20,
      //     label: '选择交易类别',
      //     // value: this.renderSettlement(),
      //     template: this.tpTransactionTypes,
      //   },
      //   {
      //     span: 4,
      //     label: 'GENERAL.INFO.OPERATION',
      // labelI18n: 'GENERAL.INFO.OPERATION',
      //     operate: true,
      //     template: this.operatorType,
      //   },
      // ])
    })
    this.pageService.setTabScrollStatus(ETabScrollStatus.Scroll)
  }

  renderSettlement(): string {
    return this.transactionTypes
      .filter(tradeType => this.data.tradeTypes.includes(tradeType.value))
      .map(tradeType => tradeType.label).join(',')
  }

  setupTradeFunctionColumns(qr: AcquirerQr) {
    this.columns[this.fields.TradeFunction].push([
      {
        span: 7,
        label: 'BIZ.STORE.OTHER.TRADE.REFUND_MODE',
        labelI18n: 'BIZ.STORE.OTHER.TRADE.REFUND_MODE',
        value: (qr.isRefundAsync !== undefined && qr.isRefundAsync),
        displayValue: this.renderRefundAsync(qr.isRefundAsync),
        index: 'isRefundAsync',
        template: this.tpRefund,
      },
      {
        span: 7,
        label: 'BIZ.STORE.OTHER.TRADE.TIPS_INSIDE_QRCODE',
        labelI18n: 'BIZ.STORE.OTHER.TRADE.TIPS_INSIDE_QRCODE',
        displayValue: this.renderYesOrNot(qr.isSupportTips),
        value: qr.isSupportTips || false,
        index: 'isSupportTips',
        template: this.tpSupportTips,
      },
      {
        span: 7,
        label: '开通固定金额收款码',
        displayValue: this.renderYesOrNot(qr.isCollectQRCodeAmountFixed),
        value: qr.isCollectQRCodeAmountFixed || false,
        index: 'isCollectQRCodeAmountFixed',
        template: this.tpFixAmount,
      },
      {
        span: 3,
        label: 'GENERAL.INFO.OPERATION',
        labelI18n: 'GENERAL.INFO.OPERATION',
        operate: true,
        template: this.operatorFunction,
      },
    ])
  }

  setupTradeWalletColumns(qr: AcquirerQr) {
    this.columns[this.fields.TradeWallet].push([
      {
        span: 10,
        label: '微信自动入网',
        displayValue: this.renderYesOrNot(qr.autoWxpApply),
        value: qr.autoWxpApply,
        index: 'autoWxpApply',
        template: this.tpWxp,
      },
      {
        span: 10,
        label: '支付宝自动入网',
        displayValue: this.renderYesOrNot(qr.autoAlpApply),
        value: qr.autoAlpApply,
        index: 'autoAlpApply',
        template: this.tpAlp,
      },
      {
        span: 4,
        label: 'GENERAL.INFO.OPERATION',
        labelI18n: 'GENERAL.INFO.OPERATION',
        operate: true,
        template: this.operatorWallet,
      },
    ])
  }

  renderYesOrNot(value: boolean): string {
    return value ? this.trans('GENERAL.INFO.YES') : this.trans('GENERAL.INFO.NO')
  }

  renderRefundAsync(value: boolean): string {
    return value ? this.trans('BIZ.STORE.OTHER.TRADE.REFUND_MODE.ASYNC') : this.trans('BIZ.STORE.OTHER.TRADE.REFUND_MODE.SYNC')
  }

  // abstract methods
  onCancel() {
    this.columns[this.field][this.rowIndex].forEach(column => {
      if (!column.index) return
      column.value = this.data[column.index]
    })
  }

  onSubmit() {
    try {
      this.columns[this.field][this.rowIndex].forEach(column => {
        if (!column.index) return

        let display = ''
        if (column.index === 'isRefundAsync') {
          display = this.renderRefundAsync(column.value as boolean)
        } else {
          display = this.renderYesOrNot(column.value as boolean)
        }
        column.displayValue = display
        this.data[column.index] = column.value
      })
      this.data['tradeTypes'] = [] // -- 二期
      this.params.feature = this.data
      const insCode = this.getID()
      this.acquirerService.updateQRFeaturesOfAcquirer(this.params, insCode).subscribe(acquirer => {
        this.commonAcquirerService.setViewingAcquirer(acquirer)
      })

      this.messageService.success(this.trans('GENERAL.NOTIFICATION.UPDATE_SUCCESS'))
    } catch (error) {
      this.messageService.error(this.trans('GENERAL.NOTIFICATION.UPDATE_FAIL'))
    }
  }

  initialColumns() {
    /*
    * 这个columns是用来收集所有需要display在这个tab里面的数据.
    * 比如 "交易币种转换" = '1', 然后交易币种转换里有一个Array = [商户交易币种, 转换交易币种, 转换汇率, 等等] 然后他在columns里就是
    * {'1': [[{商户交易币种, 转换交易币种, 转换汇率, 等等}]]}
    */
    // 现在这个trades component需要展示2个field. 这里创建2个空的Array在this.columns里的field
    for (const key in this.fields) {
      this.columns[this.fields[key]] = []
    }
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
